var app = getApp()
//常量数据配置
var ConstantData = require('../../../../common/constant_data.js')
var common = require("../../../../common/common.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    card_number:'',
    card_price:0,
    deposit_price:0,
    card_desc:'此包时卡已失效',
    card_img:'https://www.ejiakanghu.com.cn/mini/temp_time_card.jpg',
    pay_stat:-1,
    is_myself:0,
    is_bind:0,
    is_phone:0,
    shwoBtnStatus:false,
    card_tag:'',
    orderCode:'',
    is_expire:0,
    card_img_bind:'',
    card_img_unbind: '',
    card_img_no_active:'',
    card_img_buyed:'',
    card_img_expire:'',
    pic_txt:'',
    no_pay_time_len:0,
    card_time_len:0,
    card_type:0,
    card_phone:'',
    card_remarks:'',
    access_detail_count:5
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    console.log("time_card_detail-------")
    console.log(options)
    var cn = options.cn
    var q = options.q
    if(q) {
      q = decodeURIComponent(q)
      cn = q.substring(app.TIME_CARD_QRCODE_URL_PREFIX.length)
    }
    if(cn) {
      this.setData({
        card_number: cn
      })
    }
    
    var uuid = wx.getStorageSync('uuid');
    console.log("time card detail---uuid")
    console.log(uuid)
    if(uuid) {
      this.getTimeCardDetail()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("---time_card--------onReady")
    var that = this;
    wx.checkSession({
      success: function () {
        console.log("----------checkPass")
        that.loginHandle(true);
      },
      fail: function () {
        console.log("----------登录中")
        //登录态过期      
        that.loginAuth('', '');
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },
  /**
   * 根据卡号获取卡详情信息
   */
  getTimeCardDetail:function() {
    var that = this
    var cn = this.data.card_number
    if (cn) {
      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_time_card/detail',
          header: header,
          data: {
            cn: cn
          },
          success: function (res) {
            var backData = res.data
            console.log(res)
            console.log(backData)
            var result = backData.result
            var desc = backData.description

            if (result == -101 && that.data.access_detail_count >= 0) {
              that.getTimeCardDetail()
              that.data.access_detail_count--
              return
            }

            if (result != 0) {
              wx.showToast({
                title: desc + '(' + result + ')',
              })
              return
            }

            console.log("time_card_dtail_info....")

            var cardInfo = backData.data
            if (cardInfo == null) {
              wx.showToast({
                title: '非法的包时卡二维码',
              })
              return
            }

            that.setData({
              card_number: cn,
              shwoBtnStatus: true,
              card_price: cardInfo.cardPrice,
              deposit_price: cardInfo.depositPrice,
              card_desc: cardInfo.cardDesc,
              card_img: cardInfo.cardImg,
              is_bind: cardInfo.isBind,
              is_phone: cardInfo.isPhone,
              is_myself: cardInfo.isMyself,
              pay_stat: cardInfo.payStat,
              card_tag: cardInfo.tag,
              orderCode: cardInfo.orderCode,
              is_expire: cardInfo.isExpire,
              card_img_bind: cardInfo.cardImgBind,
              card_img_unbind: cardInfo.cardImgUnBind,
              card_img_no_active: cardInfo.cardImgNoActive,
              card_img_buyed: cardInfo.cardImgBuyed,
              card_img_expire: cardInfo.cardImgExpire,
              pic_txt: cardInfo.picTxt,
              no_pay_time_len: cardInfo.noPayTimeLen,
              card_time_len: cardInfo.cardTimeLength,
              card_type: cardInfo.cardType,
              card_phone: cardInfo.phone,
              card_remarks: cardInfo.remarks
            })

          },
          fail: function (res) {
            wx.showToast({
              title: '稍后重试',
            })
          }
        })

      })
      
    }

  },
  /**
   * 去首页
   */
  toHome:function(){
    wx.redirectTo({
      url: '../../../../pages/index/index',
    })
  },
 /**
  * 自己购买卡
  */
  buyMyself:function(){
    var isBindPhone = this.data.is_phone
    var cardNumber = this.data.card_number
    var noPayTimeLen = this.data.no_pay_time_len
    var cardTimeLen = this.data.card_time_len
    var cardType = this.data.card_type
    if(isBindPhone == 0) {
      wx.navigateTo({
        url: '../../../../pages/login/login?pt=time_card_detail&cn=' + cardNumber
      })
      return
    }

    wx.navigateTo({
      url: '../buy/buy_form?bt=1&cn=' + cardNumber + '&noPayTimeLen=' + noPayTimeLen + '&cardTimeLen=' + cardTimeLen + '&cardType=' + cardType,
    })    

  },
  /**
   * 代他人购买
   */
  buyOthers:function() {
    var isBindPhone = this.data.is_phone
    var cardNumber = this.data.card_number
    var noPayTimeLen = this.data.no_pay_time_len
    var cardTimeLen = this.data.card_time_len
    var cardType = this.data.card_type
    if (isBindPhone == 0) {
      wx.navigateTo({
        url: '../../../../pages/login/login?pt=time_card_detail&cn=' + cardNumber
      })
      return
    }

    wx.navigateTo({
      url: '../buy/buy_form?bt=2&cn=' + cardNumber + '&noPayTimeLen=' + noPayTimeLen + '&cardTimeLen=' + cardTimeLen + '&cardType=' + cardType,
    })    

  },
  /**
   * 自己支付失败的或未支付的重新支付
   */
  repeatPayMyself:function() {
    this.toPay(this.data.orderCode)
  },
  /**
   * 代他人购买支付失败的或未支付的重新支付
   */
  repeatPayOthers:function() {
    this.toPay(this.data.orderCode)
  },
  /**
   * 绑定卡所有者
   */
  bindCardUser:function() {
    var isBindPhone = this.data.is_phone
    var cardNumber = this.data.card_number
    var noPayTimeLen = this.data.no_pay_time_len
    var cardTimeLen = this.data.card_time_len
    var cardType = this.data.card_type
    if (isBindPhone == 0) {
      wx.navigateTo({
        url: '../../../../pages/login/login?pt=time_card_detail&cn=' + cardNumber ,
      })
      return
    }
    var tag = this.data.card_tag
    if(tag == null) {
      tag = ''
    }
    var cardPhone = this.data.card_phone
    var cardRemarks = this.data.card_remarks
    wx.navigateTo({
      url: '../buy/buy_form?bt=0&cn=' + cardNumber + '&tag=' + tag + '&noPayTimeLen=' + noPayTimeLen + '&cardTimeLen=' + cardTimeLen + '&cardType=' + cardType 
      +'&cardPhone='+cardPhone+'&cardRemarks='+cardRemarks,
    })   
  },

  /**
   * 调用微信进行支付
   */
  toPay: function (orderCode) {

    var that = this
    console.log("去支付。。。" + orderCode)
    app.toPayValideLogin(orderCode, function(loginCode, orderCode, err){
      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },
          success: function (res) {
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              that.setData({
                alertBoxStatus: true,
                alertBoxTipContent: data.description ? data.description:'支付失败'
              })
              return
            }
            //开始微信支付
            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function (res) {
                console.log("SUCCESS")
                console.log(res)
                //支付成功
                wx.showToast({
                  title: '支付成功',
                })
                wx.redirectTo({
                  url: '../../../../pages/index/index',
                })
              },
              fail: function (res) {
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'timeCard-' + JSON.stringify(res) : '');
              },
              complete: function (res) {
                console.log("complete--" + data.data.paySign)
                console.log(res)
              }
            })
          }
        })
  
      })    

    })


  },

  loginAuth: function (phone, pcode) {
    var that = this;
   
    //调用登录接口
    wx.login({
      success: function (res) {
        console.log(res);
        if (res.code) {
          //发起网络请求
          wx.request({
            url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/login',
            header:{
              'content-type': 'application/x-www-form-urlencoded',
            },
            method: 'post',
            data: {
              code: res.code,
              phone: phone,
              pcode: pcode
            },
            success: function (res) {
              var result = res.data.result;
              if (result == 0) {
                try {
                  wx.setStorageSync('pass', res.data.data.pass);
                  wx.setStorageSync('temp', res.data.data.temp);
                  wx.setStorageSync('ltime', res.data.data.ltime);
                  wx.setStorageSync('cpass', res.data.data.cpass);
                  wx.setStorageSync('uuid', res.data.data.uuid);
                  wx.setStorageSync('nophone', res.data.data.nophone);
                  app.globalData.loginData = res.data.data;
                } catch (e) {
                }
                console.log("登录成功开始获取卡详情信息----")
                //获取卡详情信息
                that.getTimeCardDetail()

              } else {
                if (result == 2) {
                  wx.navigateTo({
                    url: '../../../../pages/login/login',
                  });
                } else {
                  wx.showToast({
                    title: res.data.description
                  });
                }
              }
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
        
      }
    });
  
  },


  loginHandle: function (passFlg) {
    try {
      var uuid = wx.getStorageSync('uuid');
      if (uuid) {
        if (passFlg) {
          this.changePass(); //更换令牌     
        }
      } else {
        this.loginAuth('', '')
      }
    } catch (e) {
    }
  },
  changePass: function () {
    var that = this;

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/cpass',
        header: header,
        data: {
          cpass: wx.getStorageSync('cpass'),
          uuid: wx.getStorageSync('uuid'),
          oldPass: app.getUserLoginPass()
        },
        success: function (res) {
          if (res.data.result == 0) {
            wx.setStorageSync('pass', res.data.data.pass);
            wx.setStorageSync('temp', res.data.data.temp);
            wx.setStorageSync('ltime', res.data.data.ltime);
            app.globalData.loginData = res.data.data;
          } else {
            wx.navigateTo({
              url: '../../../../pages/login/login'
            })
          }
        }
      })

    })
    
  }

})